package io.gitee.luoyuan800.tool.llm.service;

import io.gitee.luoyuan800.tool.llm.agent.CommonAgent;
import io.gitee.luoyuan800.tool.llm.bean.config.AiConfig;
import io.gitee.luoyuan800.tool.llm.web.RestfulClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RequiredArgsConstructor
@Slf4j
public class AgentService {
    private final AiConfig aiConfig;
    private final RestfulClient restTemplate;
    private final Map<String, CommonAgent> agents = new HashMap<>();

    public CommonAgent getCachedAgent(String name, String overrideName, boolean cache) {
        if (cache) {
            return agents.computeIfAbsent(name, key -> createAgent(name, overrideName));
        } else {
            log.info("Create agent {} without cache.", name);
            return createAgent(name, overrideName);
        }
    }

    public CommonAgent createAgent(String name, String overrideName) {
        String displayName = Objects.toString(overrideName, name);
        log.info("Creating Agent {}({}).", displayName, name);
        return new CommonAgent(aiConfig.getAgentConfig(name), restTemplate, displayName);
    }

    public void clearCache() {
        agents.clear();
    }

    public void destroyAgent(String name) {
        agents.computeIfPresent(name, (key, agent) -> null);
    }
}
